import { validatePhoneNumber } from "../regExp/registerRuler"

interface registerUser {
    userName: string,
    password: string,
    phone: string,
    email: string,
}

interface loginUserInfo {
    loginType: number,
    userName: string,
    phoneEmail: string,
    password: string,
}

async function addUser(userInfo: registerUser) {
    let { userName, password, phone, email } = userInfo;
    let reqObj = { userName, password, phone, email };
    console.log(reqObj);
    let res = await fetch('http://127.0.0.1:3007/login/addUser', {
        method: 'post',
        headers: {
            "Content-type": "application/json",
        },
        body: JSON.stringify(reqObj)
    })

    let json = await res.json()
    return json;
}

async function loginUser(userInfo: loginUserInfo) {
    let { loginType, userName, phoneEmail, password } = userInfo;
    if (loginType === 1) {
        let reqObj = { loginType, userName, password }
        let res = await fetch('http://127.0.0.1:3007/login/loginUser', {
            method: 'post',
            headers: {
                "Content-type": "application/json",
            },
            body: JSON.stringify(reqObj)
        })

        let json = await res.json()
        return json;
    } else {
        let reqObj;
        if (validatePhoneNumber(phoneEmail)) {
            reqObj = {
                loginType,
                phone: phoneEmail,
                email: '',
                password
            }
        } else {
            reqObj = {
                loginType,
                phone: '',
                email: phoneEmail,
                password
            }
        }
        let res = await fetch('http://127.0.0.1:3007/login/loginUser', {
            method: 'post',
            headers: {
                "Content-type": "application/json",
            },
            body: JSON.stringify(reqObj)
        })

        let json = await res.json()
        return json;
    }
}

export {
    addUser,
    loginUser
};
export type { registerUser, loginUserInfo };
